{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "b022c4d3-1b80-43a3-a4e6-c175d1e98d0c",
   "metadata": {},
   "source": [
    "# 9. Keras搭建神经网络\n",
    "\n",
    "- Sequential\n",
    "- Model\n",
    "- 自制数据集\n",
    "- 训练指标可视化\n",
    "- 权值参数保存与加载\n",
    "- 模型保存与加载"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d1f20875-c50d-46df-906b-49ec1d0c6002",
   "metadata": {},
   "source": [
    "## 9.1 使用Sequential搭建神经网络实现鸢尾花分类\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "c90a18b9-d8e8-431c-856c-35f1e4ed05e1",
   "metadata": {},
   "source": [
    "### 1.任务描述\n",
    "\n",
    "搭建神经网络，实现鸢尾花分类。\n",
    "\n",
    "要求：\n",
    "- 使用Sequential搭建神经网络\n",
    "- 网络结构：单层神经网络\n",
    "- 网络的输出层使用Softmax将线性输出转换为概率分布\n",
    "- 输出迭代过程的损失和准确率\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "f5b4fc39-cbcf-432a-bf1e-e75e642d4b87",
   "metadata": {},
   "source": [
    "### 2.知识准备\n",
    "\n",
    "见教程。 "
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "c1d0295a-4ac4-470a-8263-027a3d69ac2c",
   "metadata": {},
   "source": [
    "### 3.任务分析\n",
    "\n",
    "使用Sequential搭建神经网络，可以采用六步法：\n",
    "- 导入相关模块\n",
    "- 指定输入网络的训练集和测试集，训练集特征x_train和标签y_train，测试集特征x_test和标签y_test\n",
    "- 在Sequential中逐层搭建网络结构\n",
    "- 在model.compile方法中配置训练方法，选择在训练时使用的优化器、损失函数和最终评测指标\n",
    "- 在model.fit方法中执行训练过程，告知训练集和测试集的输入值和标签、每个batch 的大小（batch_size）和数据集的迭代次数（epochs）\n",
    "- 使用model.summary方法打印网络结构，统计参数数目"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "435c6090-cfda-4f46-a550-22a368e41e4a",
   "metadata": {},
   "source": [
    "### 4.任务实施\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "ec75eb6c-5da3-467d-a471-ca3b47242dd6",
   "metadata": {},
   "source": [
    "执行代码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "2ae9da58-e339-4d22-9f8d-ca255711d89e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model: \"sequential\"\n",
      "_________________________________________________________________\n",
      " Layer (type)                Output Shape              Param #   \n",
      "=================================================================\n",
      " dense (Dense)               (None, 3)                 15        \n",
      "                                                                 \n",
      "=================================================================\n",
      "Total params: 15\n",
      "Trainable params: 15\n",
      "Non-trainable params: 0\n",
      "_________________________________________________________________\n"
     ]
    }
   ],
   "source": [
    "# 1，导入相关模块\n",
    "import tensorflow as tf\n",
    "from sklearn import datasets\n",
    "import numpy as np\n",
    "\n",
    "# 2，指定输入网络的训练集和测试集\n",
    "x_train = datasets.load_iris().data\n",
    "y_train = datasets.load_iris().target\n",
    "\n",
    "# 随机打乱数据，使用相同的seed，保证输入特征和标签一一对应\n",
    "np.random.seed(116)  \n",
    "np.random.shuffle(x_train)\n",
    "np.random.seed(116)\n",
    "np.random.shuffle(y_train)\n",
    "\n",
    "# 3，在Sequential中搭建网络结构\n",
    "model=tf.keras.models.Sequential([\n",
    "    tf.keras.layers.Dense(        \n",
    "        units=3,       \n",
    "        activation='softmax',\n",
    "        kernel_regularizer=tf.keras.regularizers.l2()\n",
    "    )\n",
    "])\n",
    "\n",
    "# 4，配置训练方法\n",
    "model.compile(\n",
    "    # 选择优化器\n",
    "    optimizer=tf.keras.optimizers.SGD(learning_rate=0.1),\n",
    "    # 选择损失函数\n",
    "    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits= False),\n",
    "    # 选择评测指标\n",
    "    metrics=['sparse_categorical_accuracy']\n",
    ")\n",
    "\n",
    "# 5，执行训练过程\n",
    "model.fit(\n",
    "    # 指定训练集输入特征\n",
    "    x_train,\n",
    "    # 指定训练集输入标签\n",
    "    y_train,\n",
    "    # 指定在训练时一次输入多少组数据\n",
    "    batch_size=128,\n",
    "    # 指定训练集迭代次数\n",
    "    epochs=300,\n",
    "    # 指定从训练集中选择多少比例的数据作为测试集\n",
    "    validation_split=0.2, \n",
    "    # 指定每迭代多少次数据集，要在测试集中验证一次准确率\n",
    "    validation_freq=10,\n",
    "    verbose=0\n",
    ")\n",
    "\n",
    "# 6，打印网络结构和统计参数数据\n",
    "model.summary()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e3b3e36e-8418-4caf-af51-d8ac80e2a321",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
